package com.greet.controller.admin;

import com.greet.dto.DishDTO;
import com.greet.dto.DishPageQueryDTO;
import com.greet.entity.Dish;
import com.greet.result.PageResult;
import com.greet.result.Result;
import com.greet.service.DishService;
import com.greet.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/admin/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/page")
    public Result<PageResult> dishPageQuery(DishPageQueryDTO dishPageQueryDTO){
        PageResult pageResult = dishService.dishPageQuery(dishPageQueryDTO);
        return Result.success(pageResult);
    }

    @PostMapping("/status/{status}")
    public Result setStatus(@PathVariable Integer status, Long id){
        DishVO dishVO = dishService.getById(id);
        Long categoryId = dishVO.getCategoryId();
        redisTemplate.delete("dish_" + categoryId);

        dishService.setStatus(status, id);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<DishVO> getById(@PathVariable Long id){
        DishVO dishVO  = dishService.getById(id);
        return Result.success(dishVO);
    }

    @GetMapping("/list")
    public Result<List<Dish>> getByCategoryId(Long categoryId){
        List<Dish> dishList = dishService.getByCategoryId(categoryId);
        return Result.success(dishList);
    }

    @Transactional(rollbackFor = Exception.class)
    @PostMapping
    public Result insertDish(@RequestBody DishDTO dishDTO){
        Long categoryId = dishDTO.getCategoryId();
        redisTemplate.delete("dish_" + categoryId);
        dishService.insertDish(dishDTO);
        return Result.success();
    }

    @Transactional(rollbackFor = Exception.class)
    @PutMapping()
    public Result updateDish(@RequestBody DishDTO dishDTO){
        clearDishCache();
        dishService.updateDish(dishDTO);
        return Result.success();
    }



    @Transactional(rollbackFor = Exception.class)
    @DeleteMapping
    public Result deleteByIds(Long[] ids){
        clearDishCache();
        dishService.deleteByIds(ids);
        return Result.success();
    }
    private void clearDishCache() {
        Set set = redisTemplate.keys("dish_*");
        redisTemplate.delete(set);
    }

}
